package com.yic.module.qms.controller.admin.inspectscheme;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.yic.framework.common.util.collection.CollectionUtils;
import com.yic.module.base.api.factory.FactoryApi;
import com.yic.module.base.api.factory.dto.FactoryRespDTO;
import com.yic.module.qms.controller.admin.inspectschemeentry.vo.InspectSchemeEntryRespVO;
import com.yic.module.qms.controller.admin.inspectschemeitem.vo.InspectSchemeItemRespVO;
import com.yic.module.qms.dal.dataobject.inspectschemeentry.InspectSchemeEntryDO;
import com.yic.module.qms.dal.dataobject.inspectschemeitem.InspectSchemeItemDO;
import com.yic.module.qms.service.inspectschemeentry.InspectSchemeEntryService;
import com.yic.module.qms.service.inspectschemeitem.InspectSchemeItemService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import com.yic.framework.common.pojo.PageResult;
import com.yic.framework.common.pojo.CommonResult;

import static com.yic.framework.common.pojo.CommonResult.success;

import com.yic.framework.excel.core.util.ExcelUtils;

import com.yic.framework.operatelog.core.annotations.OperateLog;
import static com.yic.framework.operatelog.core.enums.OperateTypeEnum.*;
import static com.yic.module.qms.enums.ErrorCodeConstants.*;

import com.yic.module.qms.controller.admin.inspectscheme.vo.*;
import com.yic.module.qms.dal.dataobject.inspectscheme.InspectSchemeDO;
import com.yic.module.qms.convert.inspectscheme.InspectSchemeConvert;
import com.yic.module.qms.service.inspectscheme.InspectSchemeService;

@Tag(name = "管理后台 - 检验方案")
@RestController
@RequestMapping("/qms/inspect-scheme")
@Validated
public class InspectSchemeController {

    @Resource
    private InspectSchemeService inspectSchemeService;
    @Resource
    private InspectSchemeItemService inspectSchemeItemService;
    @Resource
    private InspectSchemeEntryService inspectSchemeEntryService;
    @Resource
    private FactoryApi factoryApi;

    @PostMapping("/create")
    @Operation(summary = "创建检验方案")
    @PreAuthorize("@ss.hasPermission('qms:inspect-scheme:create')")
    public CommonResult<Long> createInspectScheme(@Valid @RequestBody InspectSchemeCreateReqVO createReqVO) {
        return success(inspectSchemeService.createInspectScheme(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新检验方案")
    @PreAuthorize("@ss.hasPermission('qms:inspect-scheme:update')")
    public CommonResult<Boolean> updateInspectScheme(@Valid @RequestBody InspectSchemeUpdateReqVO updateReqVO) {
        inspectSchemeService.updateInspectScheme(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除检验方案")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('qms:inspect-scheme:delete')")
    public CommonResult<Boolean> deleteInspectScheme(@RequestParam("id") Long id) {
        inspectSchemeService.deleteInspectScheme(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得检验方案")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('qms:inspect-scheme:query')")
    public CommonResult<InspectSchemeRespVO> getInspectScheme(@RequestParam("id") Long id) {
        InspectSchemeDO inspectScheme = inspectSchemeService.getInspectScheme(id);
        return success(InspectSchemeConvert.INSTANCE.convert(inspectScheme));
    }

    @GetMapping("/info")
    @Operation(summary = "获得检验方案")
    @PreAuthorize("@ss.hasPermission('qms:inspect-scheme:query')")
    public CommonResult<InspectSchemeInfoRespVO> getInspectSchemeByItem(@RequestParam("itemId") Long itemId, @RequestParam("inspectType") Integer inspectType) {
        List<InspectSchemeItemDO> nspectSchemeItemDOS = inspectSchemeItemService.getInspectSchemeItemListByItem(itemId);
        if (CollectionUtil.isEmpty(nspectSchemeItemDOS)) {
            return null;
        }
        Set<Long> schemeIds = CollectionUtils.convertSet(nspectSchemeItemDOS, InspectSchemeItemDO::getSchemeId);
        List<InspectSchemeDO> schemeList = inspectSchemeService.getInspectSchemeList(schemeIds);
        List<InspectSchemeDO> list = schemeList.stream().filter(inspectSchemeDO -> inspectSchemeDO.getInspectType().equals(inspectType)).collect(Collectors.toList());
        if (list.size()<1) {
            return null;
        }
        InspectSchemeInfoRespVO inspectSchemeInfoRespVO = InspectSchemeConvert.INSTANCE.convert01(list.get(0));
        // 获取方案详细信息
        List<InspectSchemeEntryRespVO> inspectSchemeEntryList = inspectSchemeEntryService.getInspectSchemeEntryListBySchemeId(inspectSchemeInfoRespVO.getId());
        inspectSchemeInfoRespVO.setEntryList(inspectSchemeEntryList);
        return success(inspectSchemeInfoRespVO);
    }

    @GetMapping("/list")
    @Operation(summary = "获得检验方案列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('qms:inspect-scheme:query')")
    public CommonResult<List<InspectSchemeRespVO>> getInspectSchemeList(@RequestParam("ids") Collection<Long> ids) {
        List<InspectSchemeDO> list = inspectSchemeService.getInspectSchemeList(ids);
        return success(InspectSchemeConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @Operation(summary = "获得检验方案分页")
    @PreAuthorize("@ss.hasPermission('qms:inspect-scheme:query')")
    public CommonResult<PageResult<InspectSchemeRespVO>> getInspectSchemePage(@Valid InspectSchemePageReqVO pageVO) {
        PageResult<InspectSchemeDO> pageResult = inspectSchemeService.getInspectSchemePage(pageVO);
        PageResult<InspectSchemeRespVO> resp = InspectSchemeConvert.INSTANCE.convertPage(pageResult);
        resp.getList().forEach(item->{
            FactoryRespDTO factory = factoryApi.getFactory(item.getFactoryId());
            if (ObjectUtil.isNotEmpty(factory)) {
                item.setFactoryName(factory.getName());
            }
        });
        return success(resp);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出检验方案 Excel")
    @PreAuthorize("@ss.hasPermission('qms:inspect-scheme:export')")
    @OperateLog(type = EXPORT)
    public void exportInspectSchemeExcel(@Valid InspectSchemeExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<InspectSchemeDO> list = inspectSchemeService.getInspectSchemeList(exportReqVO);
        // 导出 Excel
        List<InspectSchemeExcelVO> datas = InspectSchemeConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "检验方案.xls", "数据", InspectSchemeExcelVO.class, datas);
    }

}
